package cn.source.config;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author tubo
 */
@Component
@Slf4j
public class IdConfig {
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    /**
     * 0为赋初值 为终端ID
     */
    private long workerId = 0;
    /**
     * 数据中心ID
     */
    private long datacenterId = 1;
    private Snowflake snowflake;
    @PostConstruct
    public void init(){
        //workerId实际值
        workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr());
        log.info("当前机器的workId:{}",workerId);
        log.info("当前机器的ip:{}",NetUtil.localIps());
    }

    public IdConfig() {
        snowflake = IdUtil.createSnowflake(workerId,datacenterId);
    }

    public String snowflakeId(){
        return "GK"+snowflake.nextId();
    }

    public long snowflakeId(long workerId,long datacenterId){
        Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
        return snowflake.nextId();
    }
}
